package com.caregiver.watch.business.data.helper;

import com.caregiver.watch.business.data.model.dto.SleepCalculationData;
import com.caregiver.watch.business.data.model.dto.SleepSection;
import com.caregiver.watch.common.constant.NumberConstants;
import com.caregiver.watch.common.utils.time.DateUtils;
import org.apache.commons.collections4.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @description: 睡眠数据处理
 * @program: caregiver-watch
 * @author: 疆戟
 * @create: 2025-10-01 20:30
 */
public final class SleepDataHelper {


    /**
     * 计算睡眠得分
     *
     * @param data          睡眠数据
     * @param sleepDateTime 睡眠时间
     * @param deepSleep     深睡时长
     * @param weakSleep     浅睡时长
     * @return 睡眠得分
     */
    public static int calculateScore(SleepCalculationData data, LocalDate sleepDateTime, int deepSleep, int weakSleep) {
        LocalDateTime startTime = data.getStartTime();
        // 总睡眠时长分钟数（结束时间减去开始时间，包含清醒时长）
        int totalSleepMinutes = DateUtils.getTimeBetween(startTime, data.getEndTime(), TimeUnit.MINUTES);
        // 是指深睡百分比
        int deepSleepRatio = (deepSleep * 100 / totalSleepMinutes);
        int score;
        //判断时间入睡时间是否早于晚上 00:00
        if (startTime.isBefore(LocalDateTime.of(sleepDateTime, LocalTime.MIN))) {
            // 20+60*(1-|y-480|/480)+20*(1-|z-25|/25)-a/y*100
            score = 20;
        }  else {
            // 距离入睡时间 00:00 的分钟差
            int x = DateUtils.getTimeBetween(startTime, LocalDateTime.of(sleepDateTime, LocalTime.MIN), TimeUnit.MINUTES);
            // 20*(1-x/480)+60*(1-|y-480|/480)+20*(1-|z-25|/25)-a/y*100
            score = 20 * (1 - x / 480);
        }
        return score + 60 * (1 - Math.abs(totalSleepMinutes - 480) / 480) + 20 * (1 - Math.abs(deepSleepRatio - 25) / 25) - weakSleep / totalSleepMinutes * 100;
    }



    /**
     * 时长计算
     * @param sleepList
     */
    public static Integer getDuration(List<SleepSection> sleepList) {
        if (CollectionUtils.isEmpty(sleepList)) {
            return NumberConstants.ZERO;
        }
        return sleepList.stream().mapToInt(sleepData -> DateUtils.getTimeBetween(sleepData.getStart(), sleepData.getEnd(), TimeUnit.MINUTES)).sum();
    }
}
